package _httplient;

import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @Author: huangya
 * @Date: 2019/11/7
 * @Description:
 */
public class HttpClientProxyDemo {

    public static void main(String[] args) {
        HttpHost httpHost = new HttpHost("localhost", 8888);
        CloseableHttpClient client = HttpClients.custom()
                .setProxy(httpHost)
                .setSSLSocketFactory(createSSLConn())
                .build();
        HttpGet get = new HttpGet("http://www.baidu.com");//请求初始化
        //请求执行，获取返回对象
        CloseableHttpResponse response = null;
        try {
            response = client.execute(get);
            System.out.println(response.getStatusLine().getStatusCode());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();//关闭返回对象
                client.close();//关闭client
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 创建SSL安全连接
     *
     * @return
     */
    private static SSLConnectionSocketFactory createSSLConn() {
        SSLConnectionSocketFactory sslsf = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            sslsf = new SSLConnectionSocketFactory(sslContext);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return sslsf;
    }
}
